import time,sys
import machine
import network
import ujson
from util import display,welcome
from window import Window
from questionWindow import Button

welcome('Robot3T   V0.1')

ap = network.WLAN(network.AP_IF)
ap.active(False)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(False)

##########################
class MainWindow(Window):
	def __init__(self,title="AIbot"):
		Window.__init__(self)
		self.title = title
		
		# add your component
		self.btn_ombot = Button("Ombot",30,25,40,12)
		self.btn_ombot.cb_hold = self.cb_ombot
		Window.add(self,self.btn_ombot)

		self.btn_face = Button("Face",90,25,40,12)
		self.btn_face.cb_hold = self.cb_face
		Window.add(self,self.btn_face)

		self.btn_test = Button("Test",30,40,40,12)
		self.btn_test.cb_hold = self.cb_test
		Window.add(self,self.btn_test)

		self.btn_wifi = Button("Wifi",90,40,40,12)
		self.btn_wifi.cb_hold = self.cb_wifi
		Window.add(self,self.btn_wifi)

		Window.setTimeoutCB(self,self.cb_timeout)
		Window.setDrawCB(self,self.cb_draw)

	def run(self):
		Window.run(self)

	def cb_timeout(self):
		print("idle timeout")
		self.cb_face()

	def cb_draw(self):
		display.text(self.title,2,2,1)

	def cb_ombot(self):
		print("## Ombot Control ...")
		gc.collect()
		print("1.Free mem: ",gc.mem_free())
		from appOmt import AppOmt
		app = AppOmt(display)
		app.run()
		machine.reset()

	def cb_face(self):
		print("## Face Show ...")
		gc.collect()
		print("1.Free mem: ",gc.mem_free())
		from show import Show
		w = Show()
		w.run()
		del(w)
		del(sys.modules['show'])
		gc.collect()
		print("2.Free mem: ",gc.mem_free())
		print()
	
	def cb_test(self):
		print("## Test ...")
		gc.collect()
		print("1.Free mem: ",gc.mem_free())
		from test import TestWindow
		w = TestWindow()
		w.run()
		del(w)
		del(TestWindow)
		del(sys.modules['test'])
		gc.collect()
		print("2.Free mem: ",gc.mem_free())
		print()

	def cb_wifi(self):
		gc.collect()
		print("1.Free mem: ",gc.mem_free())
		from wifiWindow import WiFiWindow
		w = WiFiWindow()
		w.run()
		del(w)
		del(WiFiWindow)
		del(sys.modules['wifiWindow'])
		del(sys.modules['strWindow'])
		gc.collect()
		print("2.Free mem: ",gc.mem_free())
		print()

##################################
print("Free mem: ",gc.mem_free())
print(sys.modules)

print("Hold or click.")

mw = MainWindow(title="Main Menu")
mw.run()
del(mw)
gc.collect() # very import!!!
print("Free mem: ",gc.mem_free())
